<?php 
class Plugin {

	protected $view;
	protected $_plug_name;
	protected $_plug_controller;
	protected $_plug_action;
	protected $_plug_path;
	protected $_admin_auth = 0; //管理员权限

	function __construct() {

		if ($this -> _admin_auth && !\mylib\Session::get('admin_login')) {
			\mylib\Response::redirect(\mylib\Route::buildUrl('/admin/index/index'));
		}

		$this -> _plug_name = $this -> convertUnderline(\mylib\Input::param('_plug_name', '', function($str){
			return preg_replace('/[^a-zA-Z]+/','',$str);
		}));
		$this -> _plug_controller = $this -> convertUnderline(ucfirst(\mylib\Input::param('_plug_controller', '', function($str){
			return preg_replace('/[^a-zA-Z]+/','',$str);
		})));
		$this -> _plug_action = $this -> convertUnderline(\mylib\Input::param('_plug_action', '', function($str){
			return preg_replace('/[^a-zA-Z]+/','',$str);
		}));
		
		$this -> _plug_path = PROJECT_PATH . 'plugin/'.($this -> _plug_name).'/';

		$this -> view = new \mylib\View(array_merge(\mylib\Config::get('view'), [
			'module_path' => PROJECT_PATH . 'plugin/'.($this -> _plug_name).'/view/',
			'theme'=>''
		]));
	}

	protected function assign($data=[], $value=null){
		$this -> view -> assign($data, $value);
		return $this -> view;
	}

	protected function fetch($tpl=null, $data=[]){
		if (!$tpl) {
			$tpl = $this -> _plug_action;
		}
		if (0 === strpos($tpl, '/')) {
			$file = PROJECT_PATH . 'plugin/'.($this -> _plug_name).'/view/' . $tpl . '.php';
		}else{
			$file = PROJECT_PATH . 'plugin/'.($this -> _plug_name).'/view/' . (strtolower($this -> _plug_controller)) . '/' . $tpl . '.php';
		}
		return $this -> view -> fetch($file, $data);
	}

	protected function html($html = ''){
		return \mylib\Response::html($html);
	}

	protected function success($message='操作成功！', $url='', $data=[]){
		if (\Ebcms::isAjax()) {
			return \mylib\Response::json([
				'code'=>1,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]);
		}else{
			return \mylib\Response::html($this -> assign([
				'code'=>1,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]) -> fetch(PROJECT_PATH . 'app/admin/view/common/notice.php'));
		}
	}

	protected function error($message='操作失败！', $url='', $data=[]){
		if (\Ebcms::isAjax()) {
			return \mylib\Response::json([
				'code'=>0,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]);
		}else{
			return \mylib\Response::html($this -> assign([
				'code'=>0,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]) -> fetch(PROJECT_PATH . 'app/admin/view/common/notice.php'));
		}
	}

	private function convertUnderline($str){
		return preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
			return strtoupper($matches[2]);
		}, $str);
	}

	public static function plugins($name=null){
		if (!$plugins = \mylib\Cache::get('plugins')) {
			$dir = PROJECT_PATH . 'plugin/';
			$plugins = [];
			if (is_dir($dir)) {
			    $dh = opendir($dir);
			    while ($file = readdir($dh)) {
			        if ($file != "." && $file != "..") {
			            $fullpath = $dir . "/" . $file;
			            if (is_dir($fullpath)) {
			            	if (file_exists($fullpath . '/_config.php')) {
			            		$_config = include $fullpath . '/_config.php';
			            		$plugins[$file] = $_config;
			            	}
			            }
			        }
			    }
			}
			\mylib\Cache::set('plugins', $plugins, 3600);
		}
		return is_null($name)?$plugins:(isset($plugins[$name])?$plugins[$name]:null);
	}

	// 注入插件的hook
	public static function hook(){
		foreach (\Plugin::plugins() as $plugin => $config) {
			if ($config['status'] && $config['hooks']) {
				foreach ($config['hooks'] as $hook) {
					\mylib\Hook::reg($hook, function(&$params) use ($plugin, $hook){
						if (file_exists(PROJECT_PATH . 'plugin/' . $plugin . '/config.php')) {
							$cfg = require PROJECT_PATH . 'plugin/' . $plugin . '/config.php';
							if (isset($cfg['hooks'][$hook]) && is_array($cfg['hooks'][$hook])) {
								foreach ($cfg['hooks'][$hook] as $value) {
									if (is_callable($value)) {
										$value($params);
									}else{
										require PROJECT_PATH . 'plugin/' . $plugin . '/hook/' . $value . '.php';
										$class = '\\plugin\\hook\\'.$value;
										$class::run($params);
									}
								}
							}
						}
					});
				}
			}
		}
	}

	// 生成插件url
	public static function url($path, $query=[], $type=0){
		$p = array_values(array_filter(explode('/', $path)));
		if (count($p) == 3) {
			$name = $p[0];
			$controller = $p[1];
			$action = $p[2];
		}elseif (count($p) == 2) {
			$name = \mylib\Input::param('_plug_name');
			$controller = $p[0];
			$action = $p[1];
		}elseif (count($p) == 1) {
			$name = \mylib\Input::param('_plug_name');
			$controller = \mylib\Input::param('_plug_controller');
			$action = $p[0];
		}else{
			throw new \Exception("插件url生成参数错误");
		}
		if ($type) {
			return \mylib\Route::buildUrl('/home/plugin/index', array_merge([
				'_plug_name' => $name,
				'_plug_controller' => $controller,
				'_plug_action' => $action,
			], $query));
		}else{
			return \mylib\Route::buildUrl('/home/plugin/index', [
				'_plug_name' => $name,
				'_plug_controller' => $controller,
				'_plug_action' => $action,
			]) . ($query?'?' . http_build_query($query):'');
		}
	}
}